package GUI;

import Ctr.AttendanceCtr;
import DB.CourseDB;
import DB.SessionDB;
import DB.StudentDB;
import DB.TeamDB;
import Model.*;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

public class TeacherGUI extends JFrame {
    private JPanel pnlMain;
    private JTabbedPane tabTeacherTabs;
    private JPanel pnlStudent;
    private JPanel pnlCourse;
    private JLabel lblTeacherName;
    private JLabel lblDate;
    private JTextField txtCourseDate;
    private JLabel lblCourseInfo;
    private JButton btnCourseComment;
    private JTable tblCourseAttendance;
    private JScrollPane scrCourseScrollPane;
    private JButton btnCourseChangeAttendance;
    private JTextField txtCourseAttendanceComment;
    private JComboBox cmbCourseDateChange;
    private JList lstStudentAttendance;
    private JPanel pnlStudentFindStudent;
    private JPanel pnlStudentAttendance;
    private JTextField txtStudentSearchName;
    private JList lstStudentSearchResults;
    private JButton btnStudentViewAttendance;
    private JLabel lblStudentTeam;
    private JLabel lblStudentSearchList;
    private JComboBox cmbStudentTeam;
    private JPanel pnlCourseButtons;
    private JLabel lblSessionDatePicker;
    private Teacher teacher;
    private AttendanceCtr attendanceCtr;
    private String chosenDate;
    private String date;

    //Constructor
    public TeacherGUI(Teacher teacherLogin, String date) {
        setContentPane(pnlMain);
        setSize(800, 600);
        setVisible(true);
        setResizable(false);
        setTitle("UCN Attendance");
        this.date = date;
        attendanceCtr = new AttendanceCtr();

        //Chosen date is the current date
        chosenDate = date;

        //Setting the teacher to the teacher logged in
        teacher = teacherLogin;

        //Initializing drop downs, lables and jTables
        updateLabels();
        createCourseAttendanceTable();
        initializeDateDropDown();
        initializeTeamDropDown();

        //Change attendance button
        btnCourseChangeAttendance.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changeAttendance();
                createCourseAttendanceTable();
                updateLabels();
            }
        });

        //Change comment button
        btnCourseComment.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changeComment();
                txtCourseAttendanceComment.setText("");
                createCourseAttendanceTable();
                updateLabels();
            }
        });

        //Date comboBox action listener
        cmbCourseDateChange.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changeDate();
            }
        });
        cmbStudentTeam.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                findStudents();
            }
        });
        btnStudentViewAttendance.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    showStudentAttendance();
                }
                catch (NullPointerException npe) {
                    JOptionPane.showMessageDialog(pnlMain, "Markér venligst en elev!");
                }

            }
        });
    }

    //Updating labels on screen
    private void updateLabels() {
        lblTeacherName.setText("Velkommen: " + teacher.getName());
        lblDate.setText(date);
    }

    //Warning window - prints out warnings
    private void warningWindow(String message) {
        JOptionPane.showMessageDialog(pnlMain, "" + message);
    }

    //Creating/updating the course attendance table
    private void createCourseAttendanceTable() {
        try {
            ArrayList<Attendance> attendanceList = attendanceCtr.getCourseAttendanceByTeacherIDAndCurrentDate(teacher, chosenDate);
            CourseAttendanceTableModel model = new CourseAttendanceTableModel();
            model.setData(attendanceList);
            tblCourseAttendance.setModel(model);
            lblCourseInfo.setText(attendanceList.get(0).getSessionId().getCourseId().getName());
        }
        catch (NullPointerException e){
                lblCourseInfo.setText("No sessions on this date");
        }
    }

    //Changing attendance
    private void changeAttendance() {
        try {
            attendanceCtr.changeAttendance(Integer.parseInt(tblCourseAttendance.getValueAt(tblCourseAttendance.getSelectedRow(), 0).toString()),
                    attendanceCtr.getSessionByTeacherAndDate(teacher, chosenDate));
            createCourseAttendanceTable();
        }
        catch (ArrayIndexOutOfBoundsException ae) {
            warningWindow("Vælg venligst en studerende");
        }
    }

    //Changing comment
    private void changeComment() {
        try {
            if (txtCourseAttendanceComment.getText().length() > 20) {
                warningWindow("Kommentaren er for lang");
            }
            else {
                attendanceCtr.changeComment(Integer.parseInt(tblCourseAttendance.getValueAt(tblCourseAttendance.getSelectedRow(), 0).toString()),
                        attendanceCtr.getSessionByTeacherAndDate(teacher, chosenDate), txtCourseAttendanceComment.getText());
            }
        }
        catch (ArrayIndexOutOfBoundsException ae) {
            warningWindow("Vælg venligst en studerende");
        }
    }

    //Changing date
    private void changeDate() {
        chosenDate = cmbCourseDateChange.getSelectedItem().toString();
        ArrayList<Attendance> attendanceList = attendanceCtr.getCourseAttendanceByTeacherIDAndCurrentDate(teacher, chosenDate);
        CourseAttendanceTableModel model = new CourseAttendanceTableModel() ;
        model.setData(attendanceList);
        tblCourseAttendance.setModel(model);
        lblCourseInfo.setText(attendanceList.get(0).getSessionId().getCourseId().getName());
    }

    //Initialize date drop down
    private void initializeDateDropDown() {
        SessionDB sessionDB = new SessionDB();
        ArrayList<Session> sessionList = sessionDB.getAllTeacherSessions(teacher, false);

        for (Session s : sessionList) {
            cmbCourseDateChange.addItem(s.getDate().toString());
        }
    }

    //Initialize team drop down
    private void initializeTeamDropDown() {
        TeamDB teamDB = new TeamDB();
        ArrayList<Team> teamList = teamDB.getAllTeams(false);

        cmbStudentTeam.addItem("");
        cmbStudentTeam.setSelectedIndex(0);

        for (Team t : teamList) {
            cmbStudentTeam.addItem(t.getName());
        }
    }

    //Finding students in the student pane
    private void findStudents() {
        DefaultListModel dlm = new DefaultListModel();

        if (cmbStudentTeam.getSelectedIndex() != 0) {
            StudentDB studentDB = new StudentDB();
            TeamDB teamDB = new TeamDB();
            Team team = teamDB.findTeamByName(cmbStudentTeam.getSelectedItem().toString());
            ArrayList<Student> studentList = studentDB.getStudentsByTeam(team, false);

            for (Student s : studentList) {
                dlm.addElement(s);
            }

            lstStudentSearchResults.setModel(dlm);
        }
        else {
            dlm.addElement("Vælg et hold");
            lstStudentSearchResults.setModel(dlm);
        }
    }

    //Showing student attendance in the JList lstStudentAttendance
    private void showStudentAttendance() {
        DefaultListModel dlm = new DefaultListModel();
        AttendanceCtr attendanceCtr = new AttendanceCtr();

        CourseDB courseDB = new CourseDB();
        ArrayList<Course> courseList = courseDB.getAllCourses(false);

        try {
            for (Course c : courseList) {
                if (c.getId() != 0) {
                    dlm.addElement( c.getName() + ": " + attendanceCtr.getCourseAttendanceByIDAndDate((Student)lstStudentSearchResults.getSelectedValue(),c.getId(), date) + "%");
                }
            }
        }
        catch (ClassCastException ce) {
            warningWindow("Vælg et hold");
        }
        catch (NumberFormatException nfe) {
            warningWindow("Input is broken " + nfe);
        }

        dlm.addElement("Samlet: " + attendanceCtr.getAllAttendanceForOneStudentByIDAndDate((Student) lstStudentSearchResults.getSelectedValue(),date) + "%");

        lstStudentAttendance.setModel(dlm);
    }
}
